'''
签名算法类
'''
import base64
import hmac
import time
from hashlib import sha256


class genSecret(object):
    def __init__(self, secret):
        '''
        实例化对象
        :param secret:
        '''
        self.secret = secret

    def getkey(self, timestamp=-1) -> tuple:
        '''
        签名的算法：把 timestamp + "\n" + 密钥 当做签名字符串，使用 HmacSHA256 算法计算签名，再进行 Base64 编码。
        :param timestamp: 默认为-1,即自动获取当前时间戳
        :return: sign and times
        '''
        if timestamp == -1: timestamp = round(time.time()) - 2
        times = str(timestamp)
        k = f'{times}\n{self.secret}'
        key = k.encode('utf-8')
        msg = ''.encode('utf-8')
        hmac_code = hmac.new(key, msg, digestmod=sha256).digest()
        sign = base64.b64encode(hmac_code).decode('utf-8')
        return sign, times
